package com.weiaibenpao.demo.chislim.ui.activity.running;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.Polyline;
import com.amap.api.maps.model.PolylineOptions;
import com.orhanobut.logger.Logger;
import com.weiaibenpao.demo.chislim.R;
import com.weiaibenpao.demo.chislim.bean.SportOverInfoBean;
import com.weiaibenpao.demo.chislim.db.entities.RunningRecord;
import com.weiaibenpao.demo.chislim.db.preferences.RunningPreferences;
import com.weiaibenpao.demo.chislim.service.RunningService;
import com.weiaibenpao.demo.chislim.utils.Constant;
import com.weiaibenpao.demo.chislim.utils.RunningUtils;
import com.weiaibenpao.demo.chislim.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.query.Query;
/**
 * Created by ZJL on 2017/12/20
 */
public class NormalOutdoorRunActivity extends BaseOutdoorRunningActivity {
    public static final String NORMAL_RUNNING = "常规·室外";
    private ArrayList<LatLng> mLatLngList = new ArrayList<>();
    private boolean mIsStartPointDrawn;
    private LatLng mNewLatLng;
    private String mCalorie;
    private String mTotalSteps;

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        // ZJL本周：
        // 重构RunningService使之兼容室内跑--ok
        // 给趣味跑提供核心算法支持--ok it
        // 长按结束按钮写完  然后删掉RunningDataView里面的end点击处理 --ok
        // 常规跑状态恢复-- ObjectBox 查询--测试ObjectBox存储和查询--ok
        // 还是有Main盖住跑步界面,即Main界面跑到了栈顶。。--ok  caused by KeepAliveService
        // 跑步选择界面的提示，为何选择了不再显示后，偶尔还是会出来。。--ok 那是因为开启了跑步，然后结束跑步clear了Preference
        // 画起点有漏洞 --ok

    }

    @Override
    protected void putExtraToServiceIntent(Intent serviceIntent) {
        super.putExtraToServiceIntent(serviceIntent);
        serviceIntent.putExtra(RunningService.NEED_SAVE_RECORD, true);
        serviceIntent.putExtra(RunningService.NEED_EXTRA_DATA, true);
        serviceIntent.putExtra(RunningService.NEED_SAVE_STATE, true);
    }

    public static void startSelf(Context context) {
        Intent intent = new Intent(context, NormalOutdoorRunActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void restoreDataDisplay() {
        super.restoreDataDisplay();
        showAddToWhiteListNotice();
        mCurrentDistance = RunningPreferences.getInstance().getRunningDistance();
        Bundle bundle = new Bundle();
        bundle.putFloat(RunningService.DISTANCE,RunningPreferences.getInstance().getRunningDistance());
        bundle.putString(RunningService.CALORIE,RunningPreferences.getInstance().getRunningCalorie());
        bundle.putString(RunningService.PACE,RunningPreferences.getInstance().getRunningPace());
        runningDataView.setData(bundle);
        runningDataView.setTime(RunningUtils.getHmsTime((RunningPreferences.getInstance().getRunningTime())));
        restoreTraceData();
    }

    private void restoreTraceData() {
        Query<RunningRecord> query = mRunningRecordBox.query().build();
        List<RunningRecord> records = query.find();
        Logger.e("restoreTraceData records size is  "+records.size());
        if (records == null || records.size() == 0) {
            return;
        }
        int recordSize = records.size();
        List<LatLng> tempList = new ArrayList<>();
        for (int i = 0; i < recordSize; i++) {
            if(isDestroyed()) {
                return;
            }
            RunningRecord record = records.get(i);
            tempList.add(new LatLng(record.getLat(), record.getLng()));
        }
        mLatLngList.addAll(0, tempList);//保证历史数据一定在前面
    }

    @Override
    public void onDataUpdated(Bundle data) {
        super.onDataUpdated(data);
        mCalorie = data.getString(RunningService.CALORIE);
        mTotalSteps = data.getString(RunningService.STEP);
        mNewLatLng = data.getParcelable(RunningService.LAT_LNG);
        mLatLngList.add(mNewLatLng);
        if(View.VISIBLE == mapView.getVisibility()){ //只在地图对用户可见时更新地图，否则不更新
            updateMap();
        }
    }

    @Override
    protected void updateMap() {
        if (!mIsStartPointDrawn && mLatLngList.size()>0) {
            setStartMark(mLatLngList.get(0));
        }
        moveLocationMarker(mNewLatLng);
        drawTrace(mLatLngList);
    }

    private void setStartMark(LatLng latLng){
        if(latLng == null) {
            return;
        }
        View view = View.inflate(this, R.layout.mark_layout, null);
        TextView sportMark = (TextView) view.findViewById(R.id.sportTitle);
        sportMark.setText("起");
        Bitmap bitmap = convertViewToBitmap(view);
        drawMarkerOnMap(latLng, bitmap, String.valueOf("起"));
        mIsStartPointDrawn = true;
    }

    private Marker drawMarkerOnMap(LatLng point, Bitmap markerIcon, String id) {//考虑是否有必要提取到基类
        if (aMap != null && point != null) {
            return aMap
                    .addMarker(new MarkerOptions().anchor(0.5f, 1)
                            .position(point)
                            .title(id)
                            .icon(BitmapDescriptorFactory.fromBitmap(markerIcon)));
        }
        return null;
    }

    private Bitmap convertViewToBitmap(View view) {
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.buildDrawingCache();
        return view.getDrawingCache();
    }

    private Polyline traceLine;
    public void drawTrace(List<LatLng> latLngs) {//考虑是否有必要提取到基类
        if(traceLine != null){
            traceLine.remove();
            traceLine = null;
        }
        PolylineOptions polylineOptions = new PolylineOptions();
        polylineOptions.addAll(latLngs);
        polylineOptions.visible(true).width(12).zIndex(200);
        polylineOptions.color(getResources().getColor(R.color.map_trace_color));
        traceLine = aMap.addPolyline(polylineOptions);
    }



    @Override
    protected void uploadRunningData() {
        super.uploadRunningData();
        if(mAlreadyAssembled){
            doUpload();
        }else {
            Query<RunningRecord> query = mRunningRecordBox.query().build();
            List<RunningRecord> records = query.find();
            assembleDataFromDatabase(records);
            mAlreadyAssembled = true;
            doUpload();
        }
    }

    private void assembleDataFromDatabase(List<RunningRecord> records) { //可以考虑挪到BaseRunning ，因为就一个跑步组装不同，其他基本一样
        for(int i=0;i<records.size();i++){
            RunningRecord record = records.get(i);
            String timeStr = String.valueOf(record.getTime());
            mLocusPhoto.append(String.valueOf(record.getLng())).append(":").append(String.valueOf(record.getLat())).append(":").append(record.getSpeed()).append(",");
            mStridePhoto.append(timeStr).append(":").append(record.getStride()).append(",");
            mFrequencyPhoto.append(timeStr).append(":").append(record.getFrequency()).append(",");
            if(!TextUtils.isEmpty(record.getKmPace())){            //配速格式为 整公里数：配速：时间，
                mPaceForm.append(record.getKmValue()).append(":").append(record.getKmPace()).append(":").append(timeStr).append(",");
            }
            mAltitudePhoto.append(timeStr).append(":").append(record.getAltitude()).append(",");
        }
        Logger.e("上传的数据"+"坐标--" + mLocusPhoto.toString() + "  步频--" + mFrequencyPhoto + " 步幅--" + mStridePhoto + "   配速--" + mPaceForm + "  海拔--" + mAltitudePhoto);
        Logger.e("上传的数据"+"坐标size--" + mLocusPhoto.length() + "  步频size--" + mFrequencyPhoto.length() + " 步幅size--" + mStridePhoto.length() + "   配速size--" + mPaceForm.length() +
                "  海拔size--" + mAltitudePhoto.length());
    }

    private void doUpload() {
        if(isDestroyed()){
            return;
        }
        if(!Utils.isNetWorkConnected()){
            Toast.makeText(this, getString(R.string.network_not_connected), Toast.LENGTH_SHORT).show();
            return;
        }
        mPresenter.postRunData(userId,Constant.SECONDARY_TYPE_NORMAL_OUTDOOR, Constant.TYPE_NORMAL,String.valueOf(marathonType),"","",0,mCalorie,
                "",String.valueOf(mAltitudePhoto),String.valueOf(mFrequencyPhoto),String.valueOf(mStridePhoto),
                String.valueOf(mPaceForm), String.valueOf(mLocusPhoto),"",0,mTotalTime,mTotalSteps,mCurrentDistance/1000);
    }

    @Override
    public void onUploadDataSuccess(SportOverInfoBean sportInfoBean) {
        super.onUploadDataSuccess(sportInfoBean);
        ShareActivity.startSelf(this,sportInfoBean,NORMAL_RUNNING,"");
        doFinish();
    }

    @Override
    protected void onDestroy() {
        //Be sure to access view before super.onDestroy(),because they are unbound in super.onDestroy()--ZJL
        Logger.e("NormalRun onDestroy");
        super.onDestroy();
    }
}


